package org.openkoala.koala.deploy.action;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.openkoala.koala.console.ConsoleFactory;
import org.openkoala.koala.deploy.dialog.EJBConfigDialog;
import org.openkoala.koala.deploy.dialog.FileOpenDialog;
import org.openkoala.koala.deploy.ejb.pojo.EJBDeploy;
import org.openkoala.koala.deploy.ejb.pojo.EJBDeployConfig;
import org.openkoala.koala.deploy.ejb.util.EJBDeployCreate;
import org.openkoala.koala.exception.KoalaException;
import org.openkoala.koala.maven.MavenExcuter;
import org.openkoala.koala.popup.BaseAction;
import org.openkoala.koala.util.ProjectQueryUtil;

public class WarEJBDeployAction extends BaseAction {

	EJBDeploy ejbDeploy;

	String result;

	String selectedPath;
	
	@Override
	public void run(IAction arg0) {
		ConsoleFactory.showConsole();
		
		new EJBConfigDialog(new Shell(Display.getCurrent(),SWT.CLOSE),this);
		
	}
	
	public void process(final EJBDeployConfig config){
		
		try {
			selectedPath = getResource().getLocationURI().getPath();
			if (ProjectQueryUtil.isParentProject(selectedPath) == false) {
				selectedPath = selectedPath.substring(0,
						selectedPath.lastIndexOf("/"));
			}
		} catch (KoalaException e1) {
			e1.printStackTrace();
		}
		
		try {
			ProgressMonitorDialog monitorDialog = new ProgressMonitorDialog(shell);
			monitorDialog.run(true, true, new IRunnableWithProgress() {
				@Override
				public void run(IProgressMonitor monitor)
						throws InvocationTargetException, InterruptedException {
					monitor.beginTask("一键发布WAR+EJB", 2);
					monitor.worked(1);
					monitor.setTaskName("检查原项目的正确性");
					try {
						MavenExcuter.runMaven(selectedPath);
						monitor.worked(2);
						monitor.setTaskName("发布WAR+EJB...");
						config.setFilePath(selectedPath);
					    result = EJBDeployCreate.publishToEjbWar(config);
					} catch (KoalaException e) {
						e.printStackTrace();
						MessageDialog.openError(shell,
								"ERROR", e.getMessage());
					}
					monitor.done();
				}
			});
			
			FileOpenDialog dialog = new FileOpenDialog(new Shell(Display.getCurrent(),SWT.CLOSE), "EJB服务部署",result);
			dialog.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
